#! /bin/bash

# Functions zone
quit(){
  rm $temp_file_name
  exit 1
}

# Variables zone
# v0.temp file directory
location_of_temp="/home/yaufook/Documents/"
# v1.expect
location_of_expect="/usr/bin/expect"
# v2.image download folder
image_local_folder="/home/yaufook/Pictures/bing-wallpapers"
# v3.xfce wallpaper property
wallpaper_property="/backdrop/screen0/monitorLVDS/workspace0/last-image"
# v4.xfce cycle enable property
cycle_enable_property="/backdrop/screen0/monitorLVDS/workspace0/backdrop-cycle-enable"
# v5.xfce single workspace mode
single_workspace_mode_property="/backdrop/single-workspace-mode"
# v6.xfce single workspace number
single_workspace_number_property="/backdrop/single-workspace-number"

# Crate temporary file
temp_file_name=`mktemp "$location_of_temp"bing-wallpaper.XXXX`

# Use expect to telnet and get information
directory_of_expect_script=$(cd $(dirname $BASH_SOURCE) && pwd)
expect_script="$directory_of_expect_script/telnet-expect.sh"
$location_of_expect $expect_script > $temp_file_name

# Download the image
#TODO: Question1. Is this greedy match or not?
image_grep=`grep -P -o "g_img=(.*?)(.jpg)" $temp_file_name`
image_url="http://www.bing.com${image_grep#*\'}"
image_name=${image_grep##*/}
image_local_path="$image_local_folder/$image_name"
# Used to test if the url is correct
echo $image_url
if [[ ! $image_name =~ jpg$ ]]; then
  echo Download Failed.
  quit
elif [ ! -f "$image_local_path" ]; then
  wget -P $image_local_folder $image_url
fi

# Set wallpaper
#TODO: check each of the property exsists or not.
xfconf-query -c xfce4-desktop -p $wallpaper_property -s $image_local_path
xfconf-query -c xfce4-desktop -p $cycle_enable_property -s false
xfconf-query -c xfce4-desktop -p $single_workspace_mode_property -s true
xfconf-query -c xfce4-desktop -p $single_workspace_number_property -s 0

# Clear temporary file
rm $temp_file_name
